import os
import json
import threading
from django.shortcuts import render
from django.http import JsonResponse
from django.conf import settings
from app_iocs import models
from django.db.models import F
from utils import ssher
from utils.epics_dber import db_read, db_wirte


def iocs(request):
    if request.method == "GET":
        dataRet = {}

        ioc_list = list(models.Iocs.objects.filter(is_active=1).all().values('name','ip__ip'))
        dataRet['iocs'] = json.dumps(ioc_list)

        ioc_obj = models.Iocs.objects.filter(is_active=1).first()
        local_file_path = os.path.join(settings.DBS_PATH,ioc_obj.name+'.db')
        if ioc_obj.is_remote:
            remote_file_path = os.path.join(ioc_obj.file_path,ioc_obj.name+'.db')
            ssher.getRemoteFile(ioc_obj.ip.ip, ioc_obj.ip.username, ioc_obj.ip.password, remote_file_path, local_file_path)
        data = db_read(local_file_path)

        pvs = []
        for record in data['records']:
            pv = {'PVName':record['PVName'],'type':record['type'],}
            pv['fields'] = [{'key':k,'value':v} for k,v in record['fields'].items()]
            pvs.append(pv)
        dataRet['pvs'] = json.dumps(pvs)

        return render(request, 'app_iocs/iocs.html', dataRet)
    
    else:
        otype = request.POST.get('otype')
        if otype == 'getPVs':
            ioc = request.POST.get('ioc')
            ioc_obj = models.Iocs.objects.filter(name=ioc,is_active=1).first()

            local_file_path = os.path.join(settings.DBS_PATH,ioc_obj.name+'.db')
            if ioc_obj.is_remote:
                remote_file_path = os.path.join(ioc_obj.file_path,ioc_obj.name+'.db')
                ssher.getRemoteFile(ioc_obj.ip.ip, ioc_obj.ip.username, ioc_obj.ip.password, remote_file_path, local_file_path)
            data = db_read(local_file_path)

            pvs = []
            for record in data['records']:
                pv = {'PVName':record['PVName'],'type':record['type'],}
                pv['fields'] = [{'key':k,'value':v} for k,v in record['fields'].items()]
                pvs.append(pv)

            return JsonResponse({'status':True,'pvs':json.dumps(pvs)})
        
        elif otype == 'iocSave':
            ioc = request.POST.get('ioc')
            pvs = json.loads(request.POST.get('pvs'))

            ioc_obj = models.Iocs.objects.filter(name=ioc,is_active=1).first()
            local_file_path = os.path.join(settings.DBS_PATH,ioc_obj.name+'.db')

            data = {'version': 1, 'records':[], 'fileName': local_file_path}
            for pv in pvs:
                record = {'PVName':pv['PVName'],'type':pv['type'], 'fields':{}}
                for item in pv['fields']:
                    record['fields'][item['key']] = item['value']
                data['records'].append(record)
            
            db_wirte(data)
            if ioc_obj.is_remote:
                remote_file_path = os.path.join(ioc_obj.file_path,ioc_obj.name+'.db')
                ssher.putRemoteFile(ioc_obj.ip.ip, ioc_obj.ip.username, ioc_obj.ip.password, remote_file_path, local_file_path)
            thread = threading.Thread(target=ssher.callRemoteShell,
                                      args=(ioc_obj.ip.ip, ioc_obj.ip.username, ioc_obj.ip.password, ioc_obj.sh_path))
            thread.start()

            return JsonResponse({'status':True,'pvs':json.dumps(pvs)})
        
        return JsonResponse({'status':False,'err':'key error'})